package org.example.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.commmon.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


/**
 * 菜品图片的上传
 * 若要显示到前端页面 还需下载操作
 */

@Slf4j
@RestController
@RequestMapping("/common")
public class UploadController {

    @Value("${pharmacy.basePath}")
    private String basePath;

    //将上传的文件存到本地
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        log.info("文件名称:{}",file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        //后缀
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        //uuid生成新的文件名
        String newFileName = UUID.randomUUID().toString() + suffix;
        //判断当前目录是否存在
        File dir=new File(basePath);
        //不存在 则创建一个
        if (!dir.exists()){
            dir.mkdirs();
        }

        file.transferTo(new File(basePath+newFileName));
        log.info(newFileName);
        return R.success(newFileName);
    }


    @GetMapping("/download")

    /**
     * name:文件上传后的名字
     */
    public void download(String name, HttpServletResponse response) throws IOException {

        //创建输入流（从本地输入）
        FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
        //创建输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //指定文件类型
        response.setContentType("image/jpeg");

        //读取 写入
        int len=0;
        byte[] buffer=new byte[1024];

        while ((len=fileInputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }











}
